﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using MediaCenterCommander.RemoteInterfaces;
using MediaCenterCommander.UserAgent.Services;
using System.Runtime.Remoting;
using System.Threading;

namespace MediaCenterCommander.UserAgent
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MediaCenterCommanderUserAgent userAgentService;

        public MainWindow()
        {
            InitializeComponent();

            string[] args = App.CommandLineArgs;
            if (args != null && args.Length > 0 && args[0] == "/tray")
            {
                // TODO: Add option to minimize and create a tray icon.                
                this.WindowState = System.Windows.WindowState.Minimized;
            }
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            Thread t = new Thread(new ThreadStart(() =>
                {
                    RegisterRemotingService();
                }));
            t.Start();
        }

        private void RegisterRemotingService()
        {
            // TODO: Allow port to be configured.

            IDictionary props = new Hashtable();
            props["name"] = "tcp4";
            props["port"] = 9902;
            props["bindTo"] = "127.0.0.1";
            TcpChannel tcpChannel = new TcpChannel(props, null, null);
            ChannelServices.RegisterChannel(tcpChannel, false);

            this.userAgentService = new MediaCenterCommanderUserAgent();
            RemotingServices.Marshal(this.userAgentService, "IMediaCenterCommanderUserAgent");

            var uris = tcpChannel.GetUrlsForUri("IMediaCenterCommanderUserAgent");
            string uri = uris[0];
        }

        private void editOptionsMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var optionsWindow = new UI.Options.OptionsWindow();
            optionsWindow.Owner = this;
            optionsWindow.ShowDialog();
        }
    }
}
